import 'package:dss_base/utils/log_util.dart';
import 'package:flutter/material.dart';

final RouteObserver<ModalRoute<void>> routeObserver = RouteObserver<ModalRoute<void>>();

mixin PageVisibilityMixin<T extends StatefulWidget> on State<T>
implements RouteAware {

  final String tag = 'flutter_page_state_changed';

  /// 页面初始化时调用（只执行一次）
  void onPageInit() {
    Log.d('onPageInit - ${runtimeType.toString()}', tag: tag);
  }

  /// 页面可见（从其他页面返回）
  void onPageShow() {
    Log.d('onPageShow - ${runtimeType.toString()}', tag: tag);

  }

  /// 页面离开（跳转到其他页面）
  void onPageHide() {
    Log.d('onPageHide - ${runtimeType.toString()}', tag: tag);

  }

  /// 页面销毁
  void onPageDispose() {
    Log.d('onPageDispose - ${runtimeType.toString()}', tag: tag);

  }

  @override
  void initState() {
    super.initState();
    onPageInit();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route != null) {
      routeObserver.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    onPageDispose();
    super.dispose();
  }

  @override
  void didPushNext() {
    onPageHide();
  }

  @override
  void didPopNext() {
    onPageShow();
  }

  @override
  void didPush() {
  }

  @override
  void didPop() {
  }
}
